package com.baihan.angus.app.game.busshow.ui.script_library.online_exhibition.room;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.baihan.angus.app.game.basic.base.BaseResponse;
import com.baihan.angus.app.game.basic.utils.Loog;
import com.baihan.angus.app.game.basic.utils.Tooast;
import com.baihan.angus.app.game.basic.utils.net.RetrofitHelper;
import com.baihan.angus.app.game.busshow.R;
import com.baihan.angus.app.game.busshow.pop_dialog.AppDialog;
import com.baihan.angus.app.game.busshow.pop_dialog.ChooseRoleDialog;
import com.baihan.angus.app.game.busshow.pop_dialog.ClueDetailDialog;
import com.baihan.angus.app.game.busshow.pop_dialog.ClueDialog;
import com.baihan.angus.app.game.busshow.pop_dialog.GameSettingDialog;
import com.baihan.angus.app.game.busshow.pop_dialog.InviteDialog;
import com.baihan.angus.app.game.busshow.pop_dialog.MapDialog;
import com.baihan.angus.app.game.busshow.pop_dialog.NoteDialog;
import com.baihan.angus.app.game.busshow.pop_dialog.PropDetailDialog;
import com.baihan.angus.app.game.busshow.pop_dialog.PropsDialog;
import com.baihan.angus.app.game.busshow.pop_dialog.ScriptDialog;
import com.baihan.angus.app.game.common.arouter_path.ArouterAppPath;
import com.baihan.angus.app.game.common.bean.entity.ClueEntity;
import com.baihan.angus.app.game.common.bean.entity.MapEntity;
import com.baihan.angus.app.game.common.bean.response.ClueResponse;
import com.baihan.angus.app.game.common.bean.response.GetScriptResponse;
import com.baihan.angus.app.game.common.bean.response.MapResponse;
import com.baihan.angus.app.game.common.bean.response.NoteResponse;
import com.baihan.angus.app.game.common.bean.response.PropResponse;
import com.baihan.angus.app.game.common.bean.response.RoomDetailResponse;
import com.baihan.angus.app.game.common.bean.response.ScriptRole;
import com.baihan.angus.app.game.common.configs.UserConfig;
import com.baihan.angus.app.game.common.data_center.cache.GameCache;
import com.baihan.angus.app.game.common.data_center.remote.api.RoomServer;
import com.baihan.angus.app.game.common.data_center.remote.api.ScriptServer;
import com.baihan.angus.app.game.common.model.TRTCVoiceRoomCallback;
import com.baihan.angus.app.game.common.model.TRTCVoiceRoomDef;
import com.baihan.angus.app.game.common.util.media.DefMediaInfo;
import com.baihan.angus.app.game.common.util.media.IMediaInfo;
import com.baihan.angus.app.game.common.util.media.MediaGalleryActivity;
import com.blankj.utilcode.constant.PermissionConstants;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.BitmapTransitionOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.tencent.liteav.audio.TXAudioEffectManager;
import com.tencent.trtc.TRTCCloudDef;
import com.trello.rxlifecycle2.android.ActivityEvent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

import static com.baihan.angus.app.game.common.constants.BasicConstants.MSG_CANCEL_READY;
import static com.baihan.angus.app.game.common.constants.BasicConstants.MSG_DM_CHANGE_BG;
import static com.baihan.angus.app.game.common.constants.BasicConstants.MSG_DM_CHANGE_MUSIC;
import static com.baihan.angus.app.game.common.constants.BasicConstants.MSG_DM_CHOOSE_MVP;
import static com.baihan.angus.app.game.common.constants.BasicConstants.MSG_DM_SEND_BOOK;
import static com.baihan.angus.app.game.common.constants.BasicConstants.MSG_DM_SEND_MAP;
import static com.baihan.angus.app.game.common.constants.BasicConstants.MSG_DM_SEND_PROP;
import static com.baihan.angus.app.game.common.constants.BasicConstants.MSG_DM_SEND_THREAD;
import static com.baihan.angus.app.game.common.constants.BasicConstants.MSG_GAME_START;
import static com.baihan.angus.app.game.common.constants.BasicConstants.MSG_PLAYER_READ_FINISH;
import static com.baihan.angus.app.game.common.constants.BasicConstants.MSG_PLAYER_SEND_THREAD;
import static com.baihan.angus.app.game.common.constants.BasicConstants.MSG_PLAYER_TRANSFER_PROP;
import static com.baihan.angus.app.game.common.constants.BasicConstants.MSG_PLAYER_USE_PROP;
import static com.baihan.angus.app.game.common.constants.BasicConstants.MSG_READY;

/**
 * 观众进入房间
 */

@RequiresApi(api = Build.VERSION_CODES.N)
@Route(path = ArouterAppPath.VOICE_ROOM_AUDIENCE_ACTIVITY)
public class VoiceRoomAudienceActivity extends VoiceRoomBaseActivity {

    private Map<String, Integer> mInvitationSeatMap;
    private String mOwnerId;
    private boolean mIsSeatInitSuccess;
    private int mSelfSeatIndex;
    private Map<String, Object> mExitRequest = new HashMap<>();
    private Map<String, Object> mChooseRoleRequest = new HashMap<>();
    private boolean inSeat = false;
    private int newPosition, readyPosition;

    private AppDialog mAppDialog;
    private InviteDialog mInviteDialog;
    private ScriptDialog mScriptDialog;
    private NoteDialog mNoteDialog;
    private ClueDialog mClueDialog;
    private ClueDetailDialog mClueDetailDialog;
    private ChooseRoleDialog mChooseRoleDialog;
    private GameSettingDialog mGameSettingDialog;
    private PropsDialog mPropDialog;
    private PropDetailDialog mPropDetailDialog;
    private MapDialog mMapDialog;

    private List<ClueResponse.DataX> clueList = new ArrayList<>();
    private List<PropResponse.DataX> propList = new ArrayList<>();
    private List<MapEntity> mapList = new ArrayList<>();
    private List<GetScriptResponse.Data> scriptList = new ArrayList<>();
    private List<NoteResponse.Data> noteList = new ArrayList<>();

    private Map<String, Object> mSendClueRequest = new HashMap<>();
    private Map<String, Object> mOpenClueRequest = new HashMap<>();
    private Map<String, Object> mSendPropRequest = new HashMap<>();
    private Map<String, Object> mUsePropRequest = new HashMap<>();
    private Map<String, Object> mCreateNoteRequest = new HashMap<>();

    private BGMListener mBGMPlayListenr;

    public static void enterRoom(Context context, RoomDetailResponse.Data roomDetail, String roomId, String userId,
                                 int audioQuality) {
        Intent starter = new Intent(context, VoiceRoomAudienceActivity.class);
        starter.putExtra(ROOM_DETAIL, roomDetail);
        starter.putExtra(VOICEROOM_ROOM_ID, roomId);
        starter.putExtra(VOICEROOM_USER_ID, userId);
        starter.putExtra(VOICEROOM_AUDIO_QUALITY, audioQuality);
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initAudience();
        initClick();
    }

    private void initAudience() {
        tvRoomName.setText(mRoomDetail.getName());
        tvRoomId.setText("ID:" + mRoomDetail.getSn());
        mInvitationSeatMap = new HashMap<>();
        mVoiceRoomSeatAdp.notifyDataSetChanged();
        // 开始进房哦
        enterRoom();
        ibMicro.setActivated(true);
        ibMicro.setSelected(true);
        ibVolume.setActivated(true);
        ibVolume.setSelected(true);
        ibVoice.setActivated(true);
        ibVoice.setSelected(true);
        ibDmVoice.setActivated(true);
        ibDmVoice.setSelected(true);
        ibGameVolume.setActivated(true);
        ibGameVolume.setSelected(true);
        refreshView();

        //初始化bgm监听
        mBGMPlayListenr = new BGMListener();

        tvInvite.setOnClickListener(view -> {
            showInviteDialog();
        });

        //准备和取消准备
        tvReady.setOnClickListener(view -> {
            setReady(readyPosition);
        });
    }

    private void setReady(int position) {
        if (tvReady.getText().equals(getString(R.string.ready))) {
            if (inSeat) {
                sendCustomReadyMsg(position);
                tvReady.setText(getString(R.string.cancelReady));
            } else {
                Tooast.normalInfo(getString(R.string.chooseRole));
            }
        } else {
            sendCustomCancelReadyMsg(position);
            tvReady.setText(getString(R.string.ready));
        }
    }

    //玩家准备
    public void sendCustomReadyMsg(int index) {
        mTRTCVoiceRoom.sendRoomCustomMsg(MSG_READY, index + "", new TRTCVoiceRoomCallback.ActionCallback() {
            @Override
            public void onCallback(int code, String msg) {
                if (code == 0) {
                    mVoiceRoomSeatEntityList.get(index).isReady = true;
                    mVoiceRoomSeatAdp.notifyDataSetChanged();
                } else {

                }
            }
        });
    }

    //玩家取消准备
    public void sendCustomCancelReadyMsg(int index) {
        mTRTCVoiceRoom.sendRoomCustomMsg(MSG_CANCEL_READY, index + "", new TRTCVoiceRoomCallback.ActionCallback() {
            @Override
            public void onCallback(int code, String msg) {
                if (code == 0) {
                    mVoiceRoomSeatEntityList.get(index).isReady = false;
                    mVoiceRoomSeatAdp.notifyDataSetChanged();
                }
            }
        });
    }

    //玩家阅读完成
    public void sendCustomReadFinishMsg(int index) {
        mTRTCVoiceRoom.sendRoomCustomMsg(MSG_PLAYER_READ_FINISH, index + "", new TRTCVoiceRoomCallback.ActionCallback() {
            @Override
            public void onCallback(int code, String msg) {
                if (code == 0) {
                    mVoiceRoomSeatEntityList.get(index).isComplete = true;
                    mGameSeatAdp.notifyDataSetChanged();
                }
            }
        });
    }

    //玩家透露或公开线索
    public void sendCustomSendClueMsg(String roleIds) {
        mTRTCVoiceRoom.sendRoomCustomMsg(MSG_PLAYER_SEND_THREAD, roleIds, new TRTCVoiceRoomCallback.ActionCallback() {
            @Override
            public void onCallback(int code, String msg) {
                if (code == 0) {

                }
            }
        });
    }

    //玩家转交道具
    public void sendCustomTransferPropMsg(String roleIds) {
        mTRTCVoiceRoom.sendRoomCustomMsg(MSG_PLAYER_TRANSFER_PROP, roleIds, new TRTCVoiceRoomCallback.ActionCallback() {
            @Override
            public void onCallback(int code, String msg) {
                if (code == 0) {

                }
            }
        });
    }

    //玩家使用道具
    public void sendCustomUsePropMsg() {
        mTRTCVoiceRoom.sendRoomCustomMsg(MSG_PLAYER_USE_PROP, "", new TRTCVoiceRoomCallback.ActionCallback() {
            @Override
            public void onCallback(int code, String msg) {
                if (code == 0) {

                }
            }
        });
    }

    private void refreshView() {
        if (mCurrentRole == TRTCCloudDef.TRTCRoleAnchor) {
            ibMicro.setActivated(true);
            ibMicro.setSelected(true);
            ibVolume.setActivated(true);
            ibVolume.setSelected(true);
            ibVoice.setActivated(true);
            ibVoice.setSelected(true);
            ibDmVoice.setActivated(true);
            ibDmVoice.setSelected(true);
            ibGameVolume.setActivated(true);
            ibGameVolume.setSelected(true);
        } else {

        }
    }

    private void initClick() {
        llSetting.setOnClickListener(view -> {
            showGameSettingDialog();
        });

        ivScript.setOnClickListener(view -> {
            showScriptDialog();
        });

        ivClue.setOnClickListener(view -> {
            showClueDialog();
        });

        ivNote.setOnClickListener(view -> {
            getNote(mRoomDetail.getScript_id(), "note", mRoomId);
        });

        ivProps.setOnClickListener(view -> {
            showPropsDialog();
        });

        ivMap.setOnClickListener(v -> {
            showMapDialog();
        });

        ivTeamUp.setOnClickListener(v -> {

        });

        ivDeduction.setOnClickListener(v -> {

        });

    }

    private void showScriptDialog() {
        if (null == mScriptDialog) {
            mScriptDialog = new ScriptDialog(this, new ScriptDialog.Callback() {
                @Override
                public void onReaded(int position) {
                    scriptList.get(position).setRead(true);
                    mScriptDialog.refreshReaded(position);
                    //通知DM阅读完成
                    sendCustomReadFinishMsg(readyPosition);
                }
            });
        }
        mScriptDialog.initData(scriptList);
        mScriptDialog.show();
    }

    //笔记Dialog
    private void showNoteDialog(List<NoteResponse.Data> notes) {
        if (null == mNoteDialog) {
            mNoteDialog = new NoteDialog(this, new NoteDialog.Callback() {
                @Override
                public void onCreateNote(String note) {
                    createNote(note);
                }
            });
        }
        mNoteDialog.initData(notes);
        mNoteDialog.show();
    }

    private void showClueDialog() {
        if (null == mClueDialog) {
            mClueDialog = new ClueDialog(this, new ClueDialog.Callback() {
                @Override
                public void showClueDetail(int position, ClueEntity clueData) {
                    showClueDetailDialog(position, clueData);
                }
            });
        }
        mClueDialog.initData(clueList);
        mClueDialog.show();
    }

    private void showClueDetailDialog(int position, ClueEntity clueData) {
        mClueDetailDialog = new ClueDetailDialog(VoiceRoomAudienceActivity.this, new ClueDetailDialog.Callback() {
            @Override
            public void onDisclose(String clueId) {
                mSendClueRequest.put("room_sn", mRoomId);
                mSendClueRequest.put("clue_id", clueId);
                mSendClueRequest.put("action", "send");
                mSendClueRequest.put("user", "user");
                showChooseRoleDialog(position, 0, clueId, 0, 1);
            }

            @Override
            public void onOpen(String clueId) {
                mOpenClueRequest.put("room_sn", mRoomId);
                mOpenClueRequest.put("clue_id", clueId);
                mOpenClueRequest.put("action", "open");
                mOpenClueRequest.put("user", "user");
                sendClue(position, mRoomDetail.getScript_id(), mOpenClueRequest, "", "open");
            }
        });
        mClueDetailDialog.initClueData(clueData, "player");
        mClueDetailDialog.show();
    }

    private void showPropsDialog() {
        if (null == mPropDialog) {
            mPropDialog = new PropsDialog(this, new PropsDialog.Callback() {
                @Override
                public void showPropDetail(int position, PropResponse.DataX.Data propData) {
                    showPropDetailDialog(position, propData);
                }
            });
        }
        mPropDialog.initData(propList);
        mPropDialog.show();
    }

    private void showPropDetailDialog(int position, PropResponse.DataX.Data propData) {
        mPropDetailDialog = new PropDetailDialog(VoiceRoomAudienceActivity.this, new PropDetailDialog.Callback() {
            @Override
            public void onTransfer(String propId) {
                mSendPropRequest.put("room_sn", mRoomId);
                mSendPropRequest.put("prop_id", propId);
                mSendPropRequest.put("action", "send");
                mSendPropRequest.put("user", "user");
                showChooseRoleDialog(position, 1, propId, 0, 0);
            }

            @Override
            public void onUse(String propId, int useType) {
                mUsePropRequest.put("room_prop_id", propId);
                if (useType == 0) {//0-对自己使用 1-对别人使用 2-对所有人均可使用
                    mUsePropRequest.put("to_script_role_id", GameCache.chooseRoleId);
                    //使用道具
                    useProp(position, mUsePropRequest);
                } else if (useType == 1) {
                    showChooseRoleDialog(position, 2, propId, 0, 0);
                } else if (useType == 2) {
                    showChooseRoleDialog(position, 2, propId, 1, 0);
                }
            }
        });
        mPropDetailDialog.initPropData(propData);
        mPropDetailDialog.show();
    }

    private void showMapDialog() {
        if (null == mMapDialog) {
            mMapDialog = new MapDialog(this, new MapDialog.Callback() {
                @Override
                public void onShowMap(MapEntity mapData) {
                    List<IMediaInfo> iMediaInfos = new ArrayList<>();
                    iMediaInfos.add(new DefMediaInfo(mapData.getUrl().get(0).getUrl()));
                    MediaGalleryActivity.start(VoiceRoomAudienceActivity.this, iMediaInfos, 0, 1);
                }
            });
        }
        mMapDialog.initData(mapList);
        mMapDialog.show();
    }

    //选择角色
    private void showChooseRoleDialog(int position, int type, String id, int isAll, int isMulti) {//isAll:0-排除自己 1-所有人  isMulti:0-单选 1-多选
        mChooseRoleDialog = new ChooseRoleDialog(this, new ChooseRoleDialog.Callback() {
            @Override
            public void send(int type, String roleIds) {
                if (type == 0) {//0-透露线索 1-转交道具 2-使用道具
                    mSendClueRequest.put("script_role_id", roleIds);
                    sendClue(position, mRoomDetail.getScript_id(), mSendClueRequest, roleIds, "send");
                } else if (type == 1) {
                    mSendPropRequest.put("script_role_id", roleIds);
                    sendProp(position, mRoomDetail.getScript_id(), mSendPropRequest, roleIds);
                } else if (type == 2) {
                    mUsePropRequest.put("to_script_role_id", roleIds);
                    //使用道具
                    useProp(position, mUsePropRequest);
                }
                mChooseRoleDialog.dismiss();
            }
        });
        mChooseRoleDialog.initData(type, mRoomDetail.getScript_role(), isAll, isMulti);
        mChooseRoleDialog.show();
    }

    private void showGameSettingDialog() {
        if (null == mGameSettingDialog) {
            mGameSettingDialog = new GameSettingDialog(this, new GameSettingDialog.Callback() {
                @Override
                public void onInitiateDissolution() {

                }

                @Override
                public void onShareRoom() {

                }

                @Override
                public void onExitGame() {
                    onBackPressed();
                }
            });
        }
        mGameSettingDialog.setAudioEffectManager(mAudioEffectManager);
        mGameSettingDialog.setBgmId(bgmId);
        mGameSettingDialog.show();
    }

    private void enterRoom() {
//        mIsSeatInitSuccess = false;
        mSelfSeatIndex = -1;
        if (mSelfUserId.equals(mRoomDetail.getUser().getId())) {
            mCurrentRole = TRTCCloudDef.TRTCRoleAnchor;
        } else {
            mCurrentRole = TRTCCloudDef.TRTCRoleAudience;
        }

        mTRTCVoiceRoom.setSelfProfile(mUserName, mUserAvatar, null);
        mTRTCVoiceRoom.enterRoom(mRoomId, new TRTCVoiceRoomCallback.ActionCallback() {
            @Override
            public void onCallback(int code, String msg) {
                if (code == 0) {
                    //进房成功
                    mTRTCVoiceRoom.setAudioQuality(mAudioQuality);
                    tvWaitingNum.setText(mAudienceListAdapter.getItemCount() + "人");
                } else {
                    Loog.dTag("enterRoom:", "Failed " + code + ", " + msg);
                    finish();
                }
            }
        });
    }

    @Override
    public void onBackPressed() {
        if (llRoom.getVisibility() == View.VISIBLE) {
            if (tvReady.getText().equals(getString(R.string.cancelReady))) {
                Tooast.normalInfo(getString(R.string.pleaseCancelReady));
            } else {
                exitRoom();
            }
        } else if (llGame.getVisibility() == View.VISIBLE) {
            exitRoom();
        }
    }

    @Override
    public void onSeatListChange(List<TRTCVoiceRoomDef.SeatInfo> seatInfoList) {
        super.onSeatListChange(seatInfoList);
    }

    private void leaveSeat() {
        mTRTCVoiceRoom.leaveSeat(new TRTCVoiceRoomCallback.ActionCallback() {
            @Override
            public void onCallback(int code, String msg) {
                if (code == 0) {
                    inSeat = false;
                    chooseRole(newPosition);
                } else {
                    ToastUtils.showShort(getString(R.string.trtcvoiceroom_toast_offline_failure, msg));
                }
            }
        });
    }

    @Override
    public void onRecvRoomCustomMsg(String cmd, String message, TRTCVoiceRoomDef.UserInfo userInfo) {
        super.onRecvRoomCustomMsg(cmd, message, userInfo);
        if (cmd.equals(MSG_GAME_START)) {
            llRoom.setVisibility(View.GONE);
            llGame.setVisibility(View.VISIBLE);
            llDMTab.setVisibility(View.GONE);
            llPlayeTab.setVisibility(View.VISIBLE);
        } else if (cmd.equals(MSG_READY)) {//玩家准备
            int index = Integer.parseInt(message);
            mVoiceRoomSeatEntityList.get(index).isReady = true;
            mVoiceRoomSeatAdp.notifyDataSetChanged();
        } else if (cmd.equals(MSG_CANCEL_READY)) {//玩家取消准备
            int index = Integer.parseInt(message);
            mVoiceRoomSeatEntityList.get(index).isReady = false;
            mVoiceRoomSeatAdp.notifyDataSetChanged();
        } else if (cmd.equals(MSG_DM_SEND_BOOK)) {//DM发本
            //获取剧本
            getScript(mRoomDetail.getScript_id(), "script", GameCache.chooseRoleId, message, mRoomId);
        } else if (cmd.equals(MSG_PLAYER_READ_FINISH)) {//玩家阅读剧本完成
            int index = Integer.parseInt(message);
            mVoiceRoomSeatEntityList.get(index).isComplete = true;
            mGameSeatAdp.notifyDataSetChanged();
        } else if (cmd.equals(MSG_DM_SEND_THREAD)) {
            //获取DM发送的线索
            getClue(mRoomDetail.getScript_id(), "clue", mRoomId);

            //先将自己的准备状态isComplete重置
//            mVoiceRoomSeatEntityList.get(readyPosition).isComplete = false;
//            mGameSeatAdp.notifyDataSetChanged();
        } else if (cmd.equals(MSG_PLAYER_SEND_THREAD)) {
            //获取玩家发送的线索
            if (!TextUtils.isEmpty(message)) {
                String[] roleIds = message.split(",");
                for (int i = 0; i < roleIds.length; i++) {
                    if (GameCache.chooseRoleId.equals(roleIds[i])) {
                        getClue(mRoomDetail.getScript_id(), "clue", mRoomId);
                    }
                }
            } else {
                getClue(mRoomDetail.getScript_id(), "clue", mRoomId);
            }
        } else if (cmd.equals(MSG_PLAYER_TRANSFER_PROP)) {//玩家转交道具
            //获取玩家发送的道具
            if (GameCache.chooseRoleId.equals(message)) {
                getProp(mRoomDetail.getScript_id(), "prop", mRoomId);
            }
        } else if (cmd.equals(MSG_DM_SEND_PROP)) {
            //获取道具
            getProp(mRoomDetail.getScript_id(), "prop", mRoomId);
        } else if (cmd.equals(MSG_DM_SEND_MAP)) {
            //获取地图
            getMap(mRoomDetail.getScript_id(), "map", mRoomId);
        } else if (cmd.equals(MSG_DM_CHOOSE_MVP)) {
            //展示mvp
            if (GameCache.chooseRoleId.equals(message)) {

            }
        } else if (cmd.equals(MSG_DM_CHANGE_BG)) {
            changePlayerBg(message);
        } else if (cmd.equals(MSG_DM_CHANGE_MUSIC)) {
            changePlayerMusic(message);
        }
    }

    //切换场景背景图片
    private void changePlayerBg(String bgUrl) {
        Glide.with(this).asBitmap().load(bgUrl)
                .transition(BitmapTransitionOptions.withCrossFade(1000)).into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                Drawable drawable = new BitmapDrawable(resource);
                llGame.setBackground(drawable);
            }
        });
    }

    //切换场景背景音乐
    private void changePlayerMusic(String data) {
        //播放bgm
        if (!TextUtils.isEmpty(data)) {
            String[] bgmData = data.split(",");
            if (bgmId != -1) { // 已开始播放音乐，需要先停止上一次正在播放的音乐
                mAudioEffectManager.stopPlayMusic(bgmId);
            }
            bgmId = Integer.parseInt(bgmData[0]);
            bgmUrl = bgmData[1];
            audioMusicParam = new TXAudioEffectManager.AudioMusicParam(bgmId, bgmUrl);
            mAudioEffectManager.setMusicObserver(bgmId, mBGMPlayListenr);

            //设置bgm初始音量为50
            mAudioEffectManager.setMusicPlayoutVolume(bgmId, 50);
            mAudioEffectManager.setMusicPublishVolume(bgmId, 50);

            mAudioEffectManager.startPlayMusic(audioMusicParam);
        }
    }

    private void exitRoom() {
        if (null == mAppDialog) {
            mAppDialog = new AppDialog(this, new AppDialog.Callback() {
                @Override
                public void onDetermine() {
                    exit();
                }
            });
        }
        mAppDialog.setMessage(getString(R.string.exitRoom));
        mAppDialog.setDetermine(getString(R.string.determine));
        mAppDialog.setCancel(getString(R.string.cancel));
        mAppDialog.setCancelPic(getDrawable(R.mipmap.ic_cancel));
        mAppDialog.setDeterminePic(getDrawable(R.mipmap.ic_right));
        mAppDialog.show();
    }

    @SuppressLint("CheckResult")
    public void exit() {
        mExitRequest.put("user_id", UserConfig.getUserConfig().getUser().getUser_id());
        RetrofitHelper.createApi(RoomServer.class).exitRoom(mRoomId, mExitRequest).compose(this.bindUntilEvent(ActivityEvent.DESTROY))
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<BaseResponse>() {
                    @Override
                    public void accept(BaseResponse baseResponse) throws Exception {
                        if (baseResponse.getCode() == 1) {
                            mTRTCVoiceRoom.exitRoom(null);
                            mAppDialog.dismiss();
                            finish();
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        Tooast.normalInfo(throwable.getMessage());
                    }
                });
    }

    private void showInviteDialog() {
        if (null == mInviteDialog) {
            mInviteDialog = new InviteDialog(this, new InviteDialog.Callback() {
                @Override
                public void onWechat() {
                    mInviteDialog.dismiss();
                }

                @Override
                public void onQQ() {
                    mInviteDialog.dismiss();
                }
            });
        }
        mInviteDialog.show();
    }

    @Override
    public void onJoin(int position) {
//        if (mCurrentRole == TRTCCloudDef.TRTCRoleAnchor) {
//            return;
//        }
        if (inSeat) {
            if (mVoiceRoomSeatEntityList.get(readyPosition).isReady) {
                Tooast.normalInfo(getString(R.string.pleaseCancelReady));
            } else {
                newPosition = position;
                leaveSeat();
            }
        }
        chooseRole(position);

    }

    public void chooseRole(int position) {
        // 判断座位有没有人
        ScriptRole entity = mVoiceRoomSeatEntityList.get(position);
        if (!entity.isUsed) {
            PermissionUtils.permission(PermissionConstants.MICROPHONE).callback(new PermissionUtils.FullCallback() {
                @Override
                public void onGranted(List<String> permissionsGranted) {
                    mTRTCVoiceRoom.enterSeat(changeSeatIndexToModelIndex(position), new TRTCVoiceRoomCallback.ActionCallback() {
                        @Override
                        public void onCallback(int code, String msg) {
                            if (code == 0) {
                                inSeat = true;
                                chooseScriptRole(entity.getScript_role_id());
                                //记住当前准备的角色
                                readyPosition = position;
                                tvReady.setText(getString(R.string.ready));
                            } else {
                                Loog.dTag("JoinSeat", "Error code :" + ",msg :" + msg);
                            }
                        }
                    });
                }

                @Override
                public void onDenied(List<String> permissionsDeniedForever, List<String> permissionsDenied) {
                    ToastUtils.showShort(R.string.trtcvoiceroom_tips_open_audio);
                }
            }).request();
        }
    }

    @Override
    public void onRoomInfoChange(TRTCVoiceRoomDef.RoomInfo roomInfo) {
        super.onRoomInfoChange(roomInfo);
        mOwnerId = roomInfo.ownerId;
    }

    @Override
    public void onSeatMute(int index, boolean isMute) {
        super.onSeatMute(index, isMute);
    }

    @Override
    public void onAnchorEnterSeat(int index, TRTCVoiceRoomDef.UserInfo user) {
        super.onAnchorEnterSeat(index, user);
        if (user.userId.equals(mSelfUserId)) {
            mCurrentRole = TRTCCloudDef.TRTCRoleAnchor;
            mSelfSeatIndex = index;
            refreshView();
        }
    }

    @Override
    public void onAnchorLeaveSeat(int index, TRTCVoiceRoomDef.UserInfo user) {
        super.onAnchorLeaveSeat(index, user);
        if (user.userId.equals(mSelfUserId)) {
            mCurrentRole = TRTCCloudDef.TRTCRoleAudience;
            mSelfSeatIndex = -1;
//            if (mAnchorAudioPanel != null) {
//                mAnchorAudioPanel.reset();
//            }
            refreshView();
        }
    }

    @Override
    public void onRoomDestroy(String roomId) {
        super.onRoomDestroy(roomId);
        if (null == mAppDialog) {
            mAppDialog = new AppDialog(this, new AppDialog.Callback() {
                @Override
                public void onDetermine() {
                    finish();
                }
            });
        }
        mAppDialog.setMessage(getString(R.string.roomIsDissolution));
        mAppDialog.setDetermine(getString(R.string.exit));
        mAppDialog.setCancelable(false);
        mAppDialog.setCanceledOnTouchOutside(false);
        mAppDialog.show();
    }

    //获取剧本
    @SuppressLint("CheckResult")
    public void getScript(String scriptId, String type, String roleId, String sn, String roomSn) {
        RetrofitHelper.createApi(ScriptServer.class).getScript(scriptId, type, roleId, sn, roomSn)
                .compose(this.bindUntilEvent(ActivityEvent.DESTROY))
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<GetScriptResponse>() {
                    @Override
                    public void accept(GetScriptResponse getScriptResponse) throws Exception {
                        if (getScriptResponse.getCode() == 1) {
                            scriptList = getScriptResponse.getData();
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        Tooast.normalInfo(throwable.getMessage());
                    }
                });
    }

    //获取线索
    @SuppressLint("CheckResult")
    public void getClue(String scriptId, String type, String roomId) {
        RetrofitHelper.createApi(ScriptServer.class).getClue(scriptId, type, roomId)
                .compose(this.bindUntilEvent(ActivityEvent.DESTROY))
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<ClueResponse>() {
                    @Override
                    public void accept(ClueResponse clueResponse) throws Exception {
                        if (clueResponse.getCode() == 1) {
                            clueList.clear();
                            clueList.addAll(clueResponse.getData());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        Tooast.normalInfo(throwable.getMessage());
                    }
                });
    }

    //玩家转交或公开线索
    @SuppressLint("CheckResult")
    public void sendClue(int position, String scriptId, Map<String, Object> pMap, String roleIds, String sendType) {
        RetrofitHelper.createApi(ScriptServer.class).sendClue(scriptId, pMap)
                .compose(this.bindUntilEvent(ActivityEvent.DESTROY))
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<BaseResponse>() {
                    @Override
                    public void accept(BaseResponse baseResponse) throws Exception {
                        if (baseResponse.getCode() == 1) {
                            if (sendType.equals("open")) {
                                mClueDialog.refreshClueOpen(position);
                                //重新获取线索数据
                                getClue(mRoomDetail.getScript_id(), "clue", mRoomId);
                            }
                            //通知玩家刷新线索
                            sendCustomSendClueMsg(roleIds);
                            Tooast.normalInfo("发送成功");
                            mClueDetailDialog.dismiss();
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        Tooast.normalInfo(throwable.getMessage());
                        Loog.dTag("ErrorMsg", "error:" + throwable.getMessage());
                    }
                });
    }

    //获取道具
    @SuppressLint("CheckResult")
    public void getProp(String scriptId, String type, String roomId) {
        RetrofitHelper.createApi(ScriptServer.class).getProp(scriptId, type, roomId)
                .compose(this.bindUntilEvent(ActivityEvent.DESTROY))
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<PropResponse>() {
                    @Override
                    public void accept(PropResponse propResponse) throws Exception {
                        if (propResponse.getCode() == 1) {
                            propList.clear();
                            propList.addAll(propResponse.getData());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        Tooast.normalInfo(throwable.getMessage());
                    }
                });
    }

    //玩家转交道具
    @SuppressLint("CheckResult")
    public void sendProp(int position, String scriptId, Map<String, Object> pMap, String roleIds) {
        RetrofitHelper.createApi(ScriptServer.class).sendProp(scriptId, pMap)
                .compose(this.bindUntilEvent(ActivityEvent.DESTROY))
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<BaseResponse>() {
                    @Override
                    public void accept(BaseResponse baseResponse) throws Exception {
                        if (baseResponse.getCode() == 1) {
                            mPropDialog.refreshPropSend(position);
                            //重新获取道具数据
                            getProp(mRoomDetail.getScript_id(), "prop", mRoomId);
                            //通知DM道具转交
                            sendCustomTransferPropMsg(roleIds);
                            Tooast.normalInfo("转交成功");
                            mPropDetailDialog.dismiss();
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        Tooast.normalInfo(throwable.getMessage());
                        Loog.dTag("ErrorMsg", "error:" + throwable.getMessage());
                    }
                });
    }

    //使用道具
    @SuppressLint("CheckResult")
    public void useProp(int position, Map<String, Object> pMap) {
        RetrofitHelper.createApi(ScriptServer.class).useProp(pMap)
                .compose(this.bindUntilEvent(ActivityEvent.DESTROY))
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<BaseResponse>() {
                    @Override
                    public void accept(BaseResponse baseResponse) throws Exception {
                        if (baseResponse.getCode() == 1) {
                            mPropDialog.refreshPropUsed(position);
                            //重新获取道具数据
                            getProp(mRoomDetail.getScript_id(), "prop", mRoomId);
                            //通知DM道具使用
                            sendCustomUsePropMsg();
                            Tooast.normalInfo("道具使用成功");
                            mPropDetailDialog.dismiss();
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        Tooast.normalInfo(throwable.getMessage());
                    }
                });
    }

    //获取地图
    @SuppressLint("CheckResult")
    public void getMap(String scriptId, String type, String roomId) {
        RetrofitHelper.createApi(ScriptServer.class).getMap(scriptId, type, roomId)
                .compose(this.bindUntilEvent(ActivityEvent.DESTROY))
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<MapResponse>() {
                    @Override
                    public void accept(MapResponse mapResponse) throws Exception {
                        if (mapResponse.getCode() == 1) {
                            mapList.clear();
                            mapList.addAll(mapResponse.getData());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        Tooast.normalInfo(throwable.getMessage());
                    }
                });
    }

    //选择角色
    @SuppressLint("CheckResult")
    public void chooseScriptRole(String roleId) {
        mChooseRoleRequest.put("role_id", roleId);
        mChooseRoleRequest.put("user_id", UserConfig.getUserConfig().getUser().getUser_id());
        RetrofitHelper.createApi(RoomServer.class).chooseScriptRole(mRoomId, mChooseRoleRequest)
                .compose(this.bindUntilEvent(ActivityEvent.DESTROY))
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<BaseResponse>() {
                    @Override
                    public void accept(BaseResponse baseResponse) throws Exception {
                        if (baseResponse.getCode() == 1) {
                            //将选择的角色id缓存
                            GameCache.chooseRoleId = roleId;
                            Loog.dTag("chooseScriptRole", "选择角色成功, roleId = " + GameCache.chooseRoleId);
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        Tooast.normalInfo(throwable.getMessage());
                    }
                });
    }

    //创建笔记
    @SuppressLint("CheckResult")
    public void createNote(String content) {
        mCreateNoteRequest.put("room_sn", mRoomId);
        mCreateNoteRequest.put("content", content);
        RetrofitHelper.createApi(ScriptServer.class).createNote(mCreateNoteRequest)
                .compose(this.bindUntilEvent(ActivityEvent.DESTROY))
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<BaseResponse>() {
                    @Override
                    public void accept(BaseResponse baseResponse) throws Exception {
                        if (baseResponse.getCode() == 1) {
                            Tooast.normalInfo("创建笔记成功");
                            mNoteDialog.dismiss();
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        Tooast.normalInfo(throwable.getMessage());
                    }
                });
    }

    //创建笔记
    @SuppressLint("CheckResult")
    public void getNote(String scriptId, String type, String roomId) {
        RetrofitHelper.createApi(ScriptServer.class).getNote(scriptId, type, roomId)
                .compose(this.bindUntilEvent(ActivityEvent.DESTROY))
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<NoteResponse>() {
                    @Override
                    public void accept(NoteResponse noteResponse) throws Exception {
                        if (noteResponse.getCode() == 1) {
                            noteList = noteResponse.getData();
                            showNoteDialog(noteResponse.getData());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        Tooast.normalInfo(throwable.getMessage());
                    }
                });
    }

    protected Handler mHandler = new Handler(Looper.getMainLooper());

    private class BGMListener implements TXAudioEffectManager.TXMusicPlayObserver {

        @Override
        public void onStart(int i, int i1) {

        }

        @Override
        public void onPlayProgress(int id, final long curPtsMS, long durationMS) {

        }

        @Override
        public void onComplete(int id, int i1) {
            Log.d("VoiceRoomBaseActivity", "onMusicPlayFinish id " + id);
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    // 播放完成更新状态
                    mIsPlayEnd = true;
                    replayBgm();
                }
            });
        }
    }

    private void replayBgm() {
        if (mIsPlayEnd) {
            mAudioEffectManager.startPlayMusic(audioMusicParam);
            mIsPlayEnd = false;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mAudioEffectManager != null) {
            mAudioEffectManager.stopPlayMusic(bgmId);
            mAudioEffectManager = null;
        }
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
        mIsPlayEnd = false;
        mBGMPlayListenr = null;
    }
}